package com.css.session;


import cn.hutool.json.JSONUtil;

import com.css.util.GyUtils;
import com.css.util.RedisUtils;
import com.css.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.css.constant.SsoConstants.COOKIE_TOKEN_KEY;

@Slf4j
public class SessionManager {

    private static final ThreadLocal<Session> sessionManger = new ThreadLocal<Session>();


    public static Session get() {
        Session session = sessionManger.get();
        if (Objects.isNull(session)) {
            session = new Session();
            onSessionData(session);
            sessionManger.set(session);
        }
        return session;
    }
    public static void remove() {
        sessionManger.remove();
    }

    public static Session getClear() {
        return get().clear();
    }


    public static Session clear(Session session) {
        return session.clear();
    }

    private static void onSessionData(Session session) {
        try {
            String token = "";
            Cookie[] cookies = ServletUtil.getRequest().getCookies();
            if (GyUtils.isNull(cookies)) {
                token = ServletUtil.getRequest().getHeader(COOKIE_TOKEN_KEY);
            } else {
                List<Cookie> collect = Arrays.stream(cookies).filter(v -> v.getName().equals(COOKIE_TOKEN_KEY)).collect(Collectors.toList());
                if (!GyUtils.isNull(collect)) {
                    token = collect.get(0).getValue();
                }
            }
            if (GyUtils.isNotNull(token)) {
                Map yhxx = JSONUtil.toBean(RedisUtils.getHash(token, "yhxx"), Map.class);
                log.info("onSessionData通过token查询数据：{}", JSONUtil.toJsonStr(yhxx) + "；;token:" + token);
                if (GyUtils.isNotNull(yhxx)) {
                    log.info("session添加值");
                    //以下是zfjkp的session字段
                    session.setYhuuid(GyUtils.object2Str(yhxx.get("yhuuid")));
                    session.setYhlx(GyUtils.object2Str(yhxx.get("yhlx")));
                    session.setUsername(GyUtils.object2Str(yhxx.get("username")));
                    session.setPhone(GyUtils.object2Str(yhxx.get("phone")));
                    log.info("session值yhuuid:{}",session.getYhuuid()+"");
                }else{
                    log.info("session查询token中信息为空");
                }
            }
        } catch (Exception e) {
            log.info("sessionException -add", e);
        }
    }
}
